<template>
  <div>
    <div>
      <BreadX level1="商品管理" level2="参数列表"></BreadX>
    </div>
    <el-card class="mt15">
      <!-- 警告提示 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数！"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>
      <el-row class="mt15">
        <el-col>
          <span>选择商品分类：</span>
          <el-cascader
            ref="ddd"
            clearable
            v-model="checkedArr"
            :options="goodsCateData"
            :props="defaultProps"
            @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab栏 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            @click="AddManyParamsDia"
            :disabled="isOk"
            type="primary"
            size="mini"
            >添加参数</el-button
          >
          <!-- 动态参数表格 -->
          <el-table class="mt15" border :data="manyParamsData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div>
                  <el-tag
                    :key="index"
                    v-for="(item, index) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    icon="el-icon-edit"
                    size="mini"
                    type="primary"
                    @click="EditManyParamsDia(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    icon="el-icon-delete"
                    size="mini"
                    type="danger"
                    @click="deleteManParamsDia(scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
           <el-button
            @click="AddManyParamsDia"
            :disabled="isOk"
            type="primary"
            size="mini"
            >添加参数</el-button
          >
          <!-- 静态属性表格 -->
          <el-table class="mt15" border :data="onlyParamsData">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <div>
                  <el-tag
                    :key="index"
                    v-for="(item, index) in scope.row.attr_vals"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index, scope.row)"
                  >
                    {{ item }}
                  </el-tag>
                  <el-input
                    class="input-new-tag"
                    v-if="scope.row.inputVisible"
                    v-model="scope.row.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm(scope.row)"
                    @blur="handleInputConfirm(scope.row)"
                  >
                  </el-input>
                  <el-button
                    v-else
                    class="button-new-tag"
                    size="small"
                    @click="showInput(scope.row)"
                    >+ New Tag</el-button
                  >
                </div>
              </template>
            </el-table-column>
            <el-table-column label="#" type="index"></el-table-column>
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <div>
                  <el-button
                    icon="el-icon-edit"
                    size="mini"
                    type="primary"
                    @click="EditManyParamsDia(scope.row)"
                    >编辑</el-button
                  >
                  <el-button
                    icon="el-icon-delete"
                    size="mini"
                    type="danger"
                    @click="deleteManParamsDia(scope.row)"
                    >删除</el-button
                  >
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数 -->
    <el-dialog
      @close="resetForm"
      width="40%"
      title="添加动态参数"
      :visible.sync="isAddManyParamsDia"
    >
      <el-form
        :model="AddManyParamsData"
        ref="AddManyParamsRef"
        :rules="AddManyParamsRules"
      >
        <el-form-item prop="attr_name" label="动态参数" label-width="80px">
          <el-input
            v-model="AddManyParamsData.attr_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isAddManyParamsDia = false">取 消</el-button>
        <el-button type="primary" @click="AddManyParamsOk">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 编辑参数 -->
    <el-dialog
      @close="resetForm"
      width="40%"
      title="编辑静态属性"
      :visible.sync="isEditManyParamsDia"
    >
      <el-form
        :model="AddManyParamsData"
        ref="AddManyParamsRef"
        :rules="AddManyParamsRules"
      >
        <el-form-item prop="attr_name" label="动态参数" label-width="80px">
          <el-input
            v-model="AddManyParamsData.attr_name"
            autocomplete="off"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isEditManyParamsDia = false">取 消</el-button>
        <el-button type="primary" @click="EditManyParamsOk">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BreadX from "@/components/BreadX.vue";
export default {
  components: { BreadX },
  data() {
    return {
      //是否显示编辑对话框
      isEditManyParamsDia: false,
      AddManyParamsRules: {
        attr_name: [
          {
            required: true,
            message: "请输入动态参数，不能为空",
            trigger: "blur",
          },
        ],
      },
      AddManyParamsData: {
        attr_name: "",
      },
      //是否显示添加参数对话框
      isAddManyParamsDia: false,
      inputVisible: false,
      inputValue: "",
      //动态参数
      manyParamsData: [],
      //静态属性
      onlyParamsData: [],
      activeName: "many",
      //商品分类数组
      checkedArr: [],
      //商品分类
      goodsCateData: [],
      //级联配置
      defaultProps: {
        expandTrigger: "hover",
        label: "cat_name",
        children: "children",
        value: "cat_id",
        checkStrictly: true,
      },
    };
  },
  created() {
    this.getGoodsCateList();
  },
  methods: {
    //删除参数
    async deleteManParamsDia(row) {
       const res = await this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除",
        });
      });
      if (res === "confirm") {
        //调删除接口直接删除对应分类，对应参数
        const res = await this.$API.deleteManParamsAPI(this.cate_id, row.attr_id);
        //刷新参数列表
        this.getGoodsParamsList();
      }
    },
    //打开编辑对话框方法
    EditManyParamsDia(row) {
      console.log("1111");
      this.AddManyParamsData.attr_name = row.attr_name;
      this.AddManyParamsData.attr_id = row.attr_id;
      this.AddManyParamsData.attr_vals = row.attr_vals.join(",");
      this.isEditManyParamsDia = true;
    },
    //确定编辑
    EditManyParamsOk() {
      //验证表单是否有效
      this.$refs.AddManyParamsRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //调添加参数接口

        const res = await this.$API.updateGoodsParamsValsAPI(
          this.cate_id,
          this.AddManyParamsData.attr_id,
          {
            attr_name: this.AddManyParamsData.attr_name,
            attr_sel: this.activeName,
            attr_vals:this.AddManyParamsData.attr_vals,
          }
        );

        //刷新参数列表
        this.getGoodsParamsList();
        //隐藏添加参数对话框
        this.isEditManyParamsDia = false;
      });
    },
    resetForm() {
      console.log("resetForm");
      this.AddManyParamsData.attr_name = "";
    },
    //确定向后台添加新的参数
    AddManyParamsOk() {
      //验证表单是否有效
      this.$refs.AddManyParamsRef.validate(async (valid) => {
        console.log(valid);
        if (!valid) return;

        //调添加参数接口
        const res = await this.$API.addGoodsManyParamsAPI(this.cate_id, {
          attr_name: this.AddManyParamsData.attr_name,
          attr_sel: this.activeName,
        });

        //刷新参数列表
        this.getGoodsParamsList();
        //隐藏添加参数对话框
        this.isAddManyParamsDia = false;
      });
    },
    //打开动态参数对话框
    AddManyParamsDia() {
      this.isAddManyParamsDia = true;
    },
    showInput(row) {
      console.log("点击按钮时触发");
      row.inputVisible = true;
      this.$nextTick((_) => {
        this.$refs.saveTagInput.focus();
      });
    },
    //敲回车或失去焦点时添加数据，隐藏输入框并显示按钮
    async handleInputConfirm(row) {
      console.log("敲回车或失去焦点时添加数据，隐藏输入框并显示按钮");

      if (row.inputValue.trim().length === 0) return;

      //添加到数组中
      row.attr_vals.push(row.inputValue);

      //调更新参数接口，提到到后台数据库
      const res = await this.$API.updateGoodsParamsValsAPI(
        this.cate_id,
        row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(","),
        }
      );

      //隐藏当前输入框
      row.inputVisible = false;
      //清空当前输入的值
      row.inputValue = "";
      //更新参数列表
      this.getGoodsCateList();
    },
    async handleClose(index, row) {
      console.log("删除tag时的回调函数");

      //本地删除，并未更新到后台
      row.attr_vals.splice(index, 1);

      //再调用后台接口更新到后台
      const res = await this.$API.updateGoodsParamsValsAPI(
        this.cate_id,
        row.attr_id,
        {
          attr_name: row.attr_name,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(","),
        }
      );
    },
    //点击tabs栏触发
    handleClick() {
      console.log("点击tabs栏触发", this.activeName);
      this.getGoodsParamsList();
    },
    async getGoodsCateList() {
      //调分类接口
      const res = await this.$API.goodsCateListAPI();
      console.log("商品分类列表：", res);
      this.goodsCateData = res;
    },
    //级联框选择改变时触发
    handleChange() {
      console.log("级联框选择改变时触发");
      this.$refs.ddd.dropDownVisible=false
      this.getGoodsParamsList();
    },
    //获取参数列表方法
    async getGoodsParamsList() {
      console.log("获取参数列表方法");
      if (this.checkedArr.length !== 3) {
        this.$message({
          type: "error",
          message: "您需要选择3级分类，才能添加或编辑参数！",
        });

        //清空参数表格
        this.manyParamsData = [];
        //静态属性
        this.onlyParamsData = [];
        return;
      }

      //获取渲染参数列表
      const res = await this.$API.getGoodsParamsAPI(
        this.cate_id,
        this.activeName
      );

      //遍历给每个对象动态添加inputValue,inputVisible
      res.forEach((item) => {
        item.inputValue = "";
        item.inputVisible = false;
      });

      console.log("返回参数列表", res);
      if (this.activeName === "many") {
        //渲染动态参数
        res.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });

        console.log("已经转换为数组的attr_vals:", res);

        this.manyParamsData = res;
      } else if (this.activeName === "only") {
        //静态属性
        res.forEach((item) => {
          item.attr_vals =
            item.attr_vals.length > 0 ? item.attr_vals.split(",") : [];
        });

        console.log("已经转换为数组的attr_vals:", res);

        this.onlyParamsData = res;
      }
    },
  },
  computed: {
    isOk() {
      return this.checkedArr.length !== 3 ? true : false;
    },
    cate_id() {
      return this.checkedArr[this.checkedArr.length - 1];
    },
  },
};
</script>
<style >
.el-radio__inner {
  display: none;
}
.el-radio {
  position: absolute;
  width: 100%;
  height: 24px;
  margin-left: -20px;
}
</style>
<style lang="scss" scoped>
.el-cascader {
  width: 260px;
}

.el-tag {
  margin: 6px 10px;
}

.input-new-tag {
  width: 80px;
}
</style>